<template>
	<div class="coupon">
		<el-card shadow="hover">
			<div class="coupon-list mb15">
				<el-form :inline="true" :model="state.formData" label-width="70px" class="demo-form-inline">
					<el-row>
						<el-col :span="6">
							<el-form-item label="状态" style="width: 100%">
								<el-select style="width: 100%" @change="searchFun()" v-model="state.formData.state" placeholder>
									<el-option v-for="item in COUPON_STATUS_LIST" :key="item.value" :label="item.label" :value="item.value"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item label="有效期" style="width: 100%">
								<el-date-picker
									@change="searchFun()"
									v-model="state.formData.time"
									type="datetimerange"
									range-separator="To"
									start-placeholder="开始时间"
									end-placeholder="结束时间"
								></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<div style="padding-left: 10px">
								<el-button type="primary" @click="setDetailId(0)">新建优惠券</el-button>
							</div>
						</el-col>
					</el-row>
				</el-form>
			</div>
			<el-table v-loading="loading" :data="state.tableData" style="width: 100%">
				<el-table-column prop="orderNumber" label="序号"></el-table-column>
				<el-table-column prop="couponCode" label="优惠券码" width="110"></el-table-column>
				<el-table-column prop="couponName" label="优惠券名称"></el-table-column>
				<el-table-column prop="preferentialAmount" label="优惠金额"></el-table-column>
				<el-table-column prop="useSites" width="100px" label="使用站点"></el-table-column>
				<el-table-column prop="used" label="已使用"></el-table-column>
				<el-table-column label="合计优惠金额" width="110">
					<template #default="scope">
						<span v-html="scope.row.totalPreferentialAmount"></span>
					</template>
				</el-table-column>
				<el-table-column prop="startDate" label="开始日期(排序)"></el-table-column>
				<el-table-column prop="endDate" label="结束日期(排序)"></el-table-column>
				<el-table-column prop="state" label="状态"></el-table-column>
				<el-table-column label="编辑" width="160px">
					<template #default="scope">
						<el-button type="primary" @click="setDetailId(scope.row.id)">修改</el-button>
						<el-button type="danger" @click="beforeDelete(scope.row)">结束</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="onHandleSizeChange"
				@current-change="onHandleCurrentChange"
				class="mt15"
				:pager-count="5"
				:page-sizes="[10, 20, 30]"
				v-model:current-page="state.page.current"
				background
				v-model:page-size="state.page.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.page.total"
			>
			</el-pagination>
		</el-card>
		<!-- <el-dialog v-model="state.isShowCouponDialog" title="优惠券详情" width="80%" destroy-on-close>
			<CouponDetail ref="couponDetailRef" v-model:couponId="checkCouponId" @reloadList="searchFun()" />
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">取消</el-button>
					<el-button type="primary" @click="onSaveCoupon">保存</el-button>
				</span>
			</template>
		</el-dialog> -->
	</div>
</template>
<script setup name="Coupon">
import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';
import { timeFormat } from '/@/utils/filters';
import { getCommonSiteList, getCurrencyUnit, getSiteNameByShorthand } from '/@/utils/commonRequest';
import useCouponState from '/@/utils/pageState/couponState';
import { useCouponApi } from '/@/api/coupon';

const { COUPON_STATUS_LIST, FULL_MINUS, getCouponStatusText, getPreferentialamount } = useCouponState();
const { EndCoupon, getCouponList } = useCouponApi();

const couponDetailRef = ref();
const state = reactive({
	isShowCouponDialog: false,
	formData: {
		state: '', // "" 全部
		time: [null, null],
	},
	tableData: [],
	page: {
		current: 1,
		pageSize: 10,
		total: 0,
	},
});

let loading = ref(false);
let checkCouponId = ref(-1);

const $route = useRoute();

init();

function init() {
	if ($route.query.id) {
		checkCouponId.value = Number($route.query.id);
	}
	getList();
	getCommonSiteList();
}

function searchFun() {
	state.page = {
		pageSize: state.page.pageSize,
		current: 1,
		total: state.page.total,
	};
	getList();
}

async function getList() {
	if (loading.value) {
		return;
	}
	loading.value = true;

	try {
		let params = {
			current: state.page.current,
			pageSize: state.page.pageSize,
			status: state.formData.state,
			startTime: state.formData.time
				? state.formData.time[0] === null
					? null
					: dayjs(state.formData.time[0]).format('YYYY-MM-DD[T]HH:mm:ss[Z]')
				: null,
			endTime: state.formData.time
				? state.formData.time[1] === null
					? null
					: dayjs(state.formData.time[1]).format('YYYY-MM-DD[T]HH:mm:ss[Z]')
				: null,
		};
		if (state.formData.time === null) {
			params.startTime = null;
			params.endTime = null;
		}
		let res = await getCouponList(params);
		if (res.code !== 200) {
			loading.value = false;
			return;
		}
		loading.value = false;
		state.page = {
			pageSize: res.data.pageSize,
			current: res.data.current,
			total: res.data.total,
		};

		let tempList = [];
		if (res.data.length !== 0) {
			tempList = res.data.data.map((item, index) => {
				console.log('item.type', item.type);
				return {
					id: item.couponId,
					orderNumber: (res.data.current - 1) * 10 + index + 1,
					couponName: item.name,
					couponCode: item.code,
					preferentialAmount: getPreferentialamount(item.type, item.discount ? item.discount * 10 : item.amount),
					useSites: getSiteNameByShorthand(item.platformCode),
					used: item.useCount ? item.useCount : 0,
					totalPreferentialAmount: item.type === FULL_MINUS ? getCurrencyUnit(item.platformCode) + item.amountNum : '消费满1件享受折扣',
					startDate: timeFormat(item.startTime),
					endDate: timeFormat(item.endTime),
					state: getCouponStatusText(item.status),
				};
			});
		}
		state.tableData = tempList;
	} catch (error) {
		loading.value = false;
		console.error(error);
		ElMessage({
			type: 'error',
			message: '获取优惠券列表失败',
		});
	}
}

// 结束的询问
function beforeDelete(item) {
	// 提示是否结束
	ElMessageBox.confirm(`确认结束优惠券${item.couponName}？`, '结束优惠券', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			delFun(item.id);
		})
		.catch(() => {});
}

// 结束
async function delFun(id) {
	if (loading.value) {
		return;
	}
	loading.value = true;

	try {
		let res = await EndCoupon(id);
		if (res.code !== 200) {
			loading.value = false;
			return;
		}
		loading.value = false;
		ElMessage({
			type: 'success',
			message: '结束成功',
		});
		getList();
	} catch (error) {
		loading.value = false;
		ElMessage({
			type: 'error',
			message: '结束失败',
		});
	}
}

// 设置详情的id
function setDetailId(id) {
	checkCouponId.value = id;
	state.isShowCouponDialog = true;
}

const cancel = () => {
	couponDetailRef.value.cancel();
	state.isShowCouponDialog = false;
};

const onSaveCoupon = () => {
	couponDetailRef.value.submitForm();
	setTimeout(() => {
		state.isShowCouponDialog = false;
	}, 500);
};

// 分页改变
const onHandleSizeChange = (val) => {
	state.page.pageSize = val;
};
// 分页改变
const onHandleCurrentChange = (val) => {
	state.page.current = val;
	getList();
};
// 页面加载时
onMounted(() => {});
</script>
<style lang="scss" scoped></style>
